﻿using System;
using System.Threading.Tasks;
using OpenFileTransfer.Util.Net;

namespace OpenFileTransfer.Wpf.Services
{
    public class UdpService : IUdpService
    {
        public event Action<string, int, byte[]> DataReceived = (_, _, _) => { };

        private readonly UdpClientHelper _udpClientHelper;

        private readonly ILogService _logService;
        private readonly IConfigService _configService;

        public UdpService(ILogService logService, IConfigService configService)
        {
            _logService = logService;
            _configService = configService;

            _udpClientHelper = new UdpClientHelper();
            _udpClientHelper.DataReceived += OnDataReceived;
            _udpClientHelper.ErrorOccurred += OnErrorOccurred;
        }

        public void Startup()
        {
            _udpClientHelper.Start(_configService.UdpPort);
        }

        public void Shutdown()
        {
            _udpClientHelper.Stop();
        }

        public async Task SendAsync(string ip, int port, byte[] data)
        {
            try
            {
                await _udpClientHelper.SendAsync(ip, port, data);
            }
            catch (Exception e)
            {
                var message = $@"UdpClient发送数据异常：target = {ip}:{port}, {e.Message}.";
                _logService.Error(message);
            }
        }

        public async Task BroadcastAsync(int port, byte[] data)
        {
            try
            {
                await _udpClientHelper.BroadcastAsync(port, data);
            }
            catch (Exception e)
            {
                var message = $@"UdpClient广播数据异常：port = {port}, {e.Message}.";
                _logService.Error(message);
            }
        }

        private void OnDataReceived(string ip, int port, byte[] data)
        {
            DataReceived.Invoke(ip, port, data);
        }

        private void OnErrorOccurred(string message)
        {
            _logService.Error(message);
        }
    }
}
